package com.cdshop.web;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;

public final class JSONObj {
	private StringBuilder sb = new StringBuilder();
	private boolean done;

	protected JSONObj() {
	}

	public JSONObj add(String key, byte val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, short val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, int val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, long val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, float val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, double val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, boolean val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, char val) {
		this.sb.append("\"").append(key).append("\":\"").append(val)
				.append("\",");
		return this;
	}

	public JSONObj add(String key, String val) {
		this.sb.append("\"").append(key).append("\":\"").append(val)
				.append("\",");
		return this;
	}

	public JSONObj add(String key, BigDecimal val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, BigInteger val) {
		this.sb.append("\"").append(key).append("\":").append(val).append(",");
		return this;
	}

	public JSONObj add(String key, Date val) {
		this.sb.append("\"").append(key).append("\":").append(val.getTime())
				.append(",");
		return this;
	}

	public JSONObj add(String key, Object val) {
		this.sb.append("\"").append(key).append("\":\"").append(val)
				.append("\",");
		return this;
	}

	public JSONObj clear() {
		this.sb.setLength(0);
		this.done = false;
		return this;
	}

	public String value() {
		if (!this.done) {
			int len=this.sb.length();
			if(len>0){
				this.sb.setCharAt(this.sb.length() - 1, '}');
			}else{
				this.sb.append('}');
			}
			this.sb.insert(0, '{');
			this.done = true;
		}
		return this.sb.toString();
	}

	public static JSONObj instance() {
		return new JSONObj();
	}
}
